package com.hyb.algorithm.data.struct.list;

/**
 * @Author: huyanbing
 * @Date: 2021/8/14 10:26 上午
 *
 * https://leetcode-cn.com/problems/linked-list-cycle/
 * 141. 环形链表
 */
public class HasCycle {

    public static void main(String[] args) {

        //head = [3,2,0,-4], pos = 1

        ListNode head=new ListNode(3);
        head.next=new ListNode(2);
        head.next.next=new ListNode(0);
        head.next.next.next=new ListNode(-4);

        head.next.next.next=head.next.next;

        HasCycle exe=new HasCycle();
        System.out.println(exe.hasCycle(head));
    }


    public boolean hasCycle(ListNode head) {

        if (head == null || head.next == null) {
            return false;
        }

        ListNode slow = head;
        ListNode fast = head.next;

        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;

            if (slow == fast) {
                return true;
            }
        }

        return false;
    }
}
